package com.inventory.service.impl;

import com.inventory.model.PurchaseRecord;
import com.inventory.repository.PurchaseRecordRepository;
import com.inventory.service.ProductService;
import com.inventory.service.PurchaseRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class PurchaseRecordServiceImpl implements PurchaseRecordService {

    @Autowired
    private PurchaseRecordRepository purchaseRecordRepository;
    
    @Autowired
    private ProductService productService;

    @Override
    @Transactional
    public PurchaseRecord savePurchaseRecord(PurchaseRecord purchaseRecord) {
        // 保存进货记录
        PurchaseRecord savedRecord = purchaseRecordRepository.save(purchaseRecord);
        
        // 更新商品库存
        productService.updateStock(purchaseRecord.getProduct().getId(), purchaseRecord.getQuantity());
        
        return savedRecord;
    }

    @Override
    @Transactional
    public void deletePurchaseRecord(Long id) {
        Optional<PurchaseRecord> purchaseOpt = purchaseRecordRepository.findById(id);
        if (purchaseOpt.isPresent()) {
            PurchaseRecord purchase = purchaseOpt.get();
            
            // 删除进货记录前，减少相应的商品库存
            productService.updateStock(purchase.getProduct().getId(), -purchase.getQuantity());
            
            // 删除记录
            purchaseRecordRepository.deleteById(id);
        }
    }

    @Override
    public Optional<PurchaseRecord> findById(Long id) {
        return purchaseRecordRepository.findById(id);
    }

    @Override
    public List<PurchaseRecord> findAllPurchaseRecords() {
        return purchaseRecordRepository.findAll();
    }

    @Override
    public List<PurchaseRecord> findByProductId(Long productId) {
        return purchaseRecordRepository.findByProductId(productId);
    }

    @Override
    public List<PurchaseRecord> findByDateRange(LocalDateTime startDate, LocalDateTime endDate) {
        return purchaseRecordRepository.findByPurchaseDateBetween(startDate, endDate);
    }

    @Override
    public Double getTotalPurchaseAmount(LocalDateTime startDate, LocalDateTime endDate) {
        Double amount = purchaseRecordRepository.getTotalPurchaseAmountBetween(startDate, endDate);
        return amount != null ? amount : 0.0;
    }

    @Override
    public List<PurchaseRecord> findLatestPurchasesByProductId(Long productId) {
        return purchaseRecordRepository.findLatestPurchasesByProductId(productId);
    }
} 